package com.musicsonar.android.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.musicsonar.android.adapter.ResultSearchAdapter;
import com.musicsonar.android.dialog.MusicSonarDialog;
import com.musicsonar.android.utils.MusicSonarConstant;
import com.musicsonar.android.utils.MusicSonarUtils;

public class SearchActivity extends ListActivity implements Runnable {

	private ImageButton btnClear;
	private ImageButton btnConfirm;
	private EditText txtQuery;
	private LinearLayout btnBack;
	private ResultSearchAdapter adapter;
	private List<Map<String, Object>> listData;
	private Thread search;
	private String vq;
	private static SearchActivity me;
	private static MusicSonarDialog dialog;
	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.search);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header_search);
		
		btnClear = (ImageButton) findViewById(R.id.btnClear);
		btnConfirm = (ImageButton) findViewById(R.id.btnConfirm);
		txtQuery = (EditText) findViewById(R.id.txtQuery);
		btnClear.setVisibility(LinearLayout.INVISIBLE);
		btnConfirm.setVisibility(LinearLayout.INVISIBLE);

		btnBack = (LinearLayout) findViewById(R.id.back_search_header);
		btnBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
		        Log.d("CDA", "onBackPressed Called");
		        Intent intent = new Intent(me.getApplicationContext(), TabPlayListActivity.class);
		        setResult(0, intent);
		        finish();
			}
		});

		btnConfirm.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// Starting new intent
				if(dialog != null){
					dialog.dismiss();
					dialog = null;
				}
				List<Map<String, ?>> selectedList = getSelectedList();
				if(selectedList.size() > 0){
					dialog = MusicSonarDialog.show(me, getText(R.string.verifying), getText(R.string.verifying_text), true);
					VerifyThread verify = new VerifyThread(selectedList);
					verify.execute("");
				}
			}
		});

		me = this;
		search = new Thread(me);

		clearText();
		showHideClearButton();
	}

	public void clearText() {
		btnClear.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				txtQuery.setText("");
			}
		});
	}

	public void showHideClearButton(){
		txtQuery.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length() > 0){
					btnClear.setVisibility(LinearLayout.VISIBLE);
				}else{
					btnClear.setVisibility(LinearLayout.INVISIBLE);
				}
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}
			
			public void afterTextChanged(Editable s) {

			}
		});

		txtQuery.setOnKeyListener(new View.OnKeyListener() {
			
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_ENTER){
					if(dialog != null){
						dialog.dismiss();
						dialog = null;
					}
					dialog = MusicSonarDialog.show(me, getText(R.string.loading), getText(R.string.loading_wait), true);
					InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					if(mgr.isActive()){
						mgr.hideSoftInputFromWindow(txtQuery.getWindowToken(), 0);
					}
					vq = txtQuery.getText().toString();
					if(vq.trim().length() > 0){
						if(MusicSonarUtils.isOnline(me)){
							adapter = null;
							listData = null;
							if(!search.isAlive()){
								search.start();
							}
							//Toast.makeText(me, getText(R.string.search_add_message), Toast.LENGTH_LONG).show();
							return true;
						}else{
							Toast.makeText(dialog.getContext(), "Can't connect to internet", Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							dialog = null;
							return true;
						}
					}else{
						Toast.makeText(dialog.getContext(), "Enter search criteria", Toast.LENGTH_SHORT).show();
						dialog.dismiss();
						dialog = null;
						return true;
					}
				}
				return false;
			}
		});
	}

	public void run() {
		try{
			vq = vq.replace(" ", "+");
			String url_query = MusicSonarConstant.SERVER_URL_LINK+"search/?vq="+vq+"&start-index=1&max-results=10";
			if(adapter != null){
				url_query = adapter.getURLQuery();
			}
			position = listData != null ? (listData.size() - 9 > 0 ? listData.size() - 9 : 0) : 0;
			adapter = new ResultSearchAdapter(me, url_query, listData, R.layout.search_item, new String[] { "songImage", "songTitle", "songDuration", "index" }, new int[] { R.id.songImage, R.id.songTitle, R.id.songDuration, R.id.songSelected }, false);
			listData = adapter.getData();
			handler.sendEmptyMessage(0);
		}catch(Exception e){
			Toast.makeText(me, e.getMessage(), Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			dialog = null;
		}
	}

	private List<Map<String, ?>> getSelectedList(){
		List<Map<String, Object>> screenList = new ArrayList<Map<String, Object>>();
		if(getListAdapter() != null){
			screenList = ((ResultSearchAdapter)getListAdapter()).getData();
		}
		List<Map<String, ?>> selectedList = new ArrayList<Map<String, ?>>();
		for(int i = 0; i < screenList.size(); i ++){
			Map<String, ?> _item = screenList.get(i);
			Boolean isSelected = (Boolean)_item.get("songSelected");
			if(isSelected){
				selectedList.add(_item);
			}
		}
		return selectedList;
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(!search.isInterrupted()){
				search.interrupt();
			}
			search = new Thread(me);
			dialog.dismiss();
			dialog = null;
			setListAdapter(adapter);
			listData = adapter.getData();
			// selecting single ListView item
			ListView lv = getListView();

			lv.setSelection(position);

			lv.setOnScrollListener(new OnScrollListener() {
				
				public void onScrollStateChanged(AbsListView view, int scrollState) {

				}
				
				public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int _totalItemCount) {
					boolean loadMore = firstVisibleItem + visibleItemCount >= _totalItemCount;
					if(_totalItemCount > -1 && _totalItemCount > 9){
						if (loadMore) {
							if(!search.isAlive()){
								if(dialog != null){
									dialog.dismiss();
									dialog = null;
								}
								dialog = MusicSonarDialog.show(me, getText(R.string.loading), getText(R.string.loading_wait), true);
								try{
									search.start();
								}catch(Exception e){}
							}
						}
					}
				}
			});

			if(listData.size() > 0){
				btnConfirm.setVisibility(LinearLayout.VISIBLE);
			}

			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> list, View view, int position, long id) {
					List<Map<String, ?>> selectedList = getSelectedList();
					if(selectedList.size() > 0){
						btnConfirm.setVisibility(LinearLayout.VISIBLE);
					}else{
						btnConfirm.setVisibility(LinearLayout.INVISIBLE);
					}
				}
			});
		}
	};

	private class VerifyThread extends AsyncTask<String, String, Void> {

		private List<Map<String, ?>> selectedList;
		private int indice = 0;
		private boolean isError = false;
		private boolean isNoFound = false;
		private String message = "";

		public VerifyThread(List<Map<String, ?>> selectedList){
			this.selectedList = selectedList;
		}

		protected Void doInBackground(String... params) {
			try{
				ArrayList<Map<String, ?>> resultValidate = new ArrayList<Map<String, ?>>();
				for(int i = 0; i < selectedList.size(); i ++){
					indice ++;
					Map<String, ?> item = selectedList.get(i);
					String title = (String)item.get("songTitle");
					publishProgress(getText(R.string.verifying_progress_text) + " [" + title + "] - " + (indice) + "/" + selectedList.size());
					if(MusicSonarUtils.verifyURL((String)item.get("songYT"))){
						item.remove("songSelected");
						resultValidate.add(item);
					}
				}
				if(resultValidate.size() > 0){
					// Sending songIndex to TabPlayerActivity
					Intent intentTarget = new Intent(me, TabPlayListActivity.class);
					intentTarget.putExtra("songSelected", resultValidate);
					setResult(100, intentTarget);
					// Closing PlayListView
					finish();
				}else{
					isNoFound = true;
				}
			}catch(Exception e){
				message = e.getMessage();
				isError = true;
			}
			return null;
		}

		protected void onProgressUpdate(String... progress) {
			MusicSonarUtils.setProcessMessage(dialog, progress[0]);
		}

		protected void onPostExecute(Void result) {
			if(indice >= selectedList.size()){
				if(dialog != null){
					dialog.dismiss();
					dialog = null;
				}
			}
			if(isError){
				if(dialog != null){
					dialog.dismiss();
					dialog = null;
				}
				MusicSonarUtils.showToast(me, message);
			}
			if(isNoFound){
				if(dialog != null){
					dialog.dismiss();
					dialog = null;
				}
				MusicSonarUtils.showToast(me,getText(R.string.validate_cant));
			}
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Configuration c = getResources().getConfiguration();
		if(c.orientation == Configuration.ORIENTATION_PORTRAIT ) {
			Toast.makeText(me, "ORIENTATION_PORTRAIT", Toast.LENGTH_SHORT);
		} else if(c.orientation == Configuration.ORIENTATION_LANDSCAPE ){
			Toast.makeText(me, "ORIENTATION_LANDSCAPE", Toast.LENGTH_SHORT);
		}
	}
}